#include "drv_slave_iic.h"
#include "bsp_register_map.h"
#include <stdio.h>
#include "cola_os.h"

void (*read_commod)(uint8_t*);
extern void logWrite(const char *fmt, ...);
static task_t *pSlaveRxTask = NULL;
ST_SLAVE_I2C_DATA g_stSlaveIIC;

void IIC_callback(i2c_slave_event_t slaveEvent, void *userData)
{
//	/* Get instance number from userData */
	i2c_instance_t * instance;
	instance = (i2c_instance_t *) userData;

	if (slaveEvent == I2C_SLAVE_EVENT_RX_REQ)
	{//948 Write
		if(g_stSlaveIIC.rxbuf != NULL)
			I2C_SlaveSetRxBuffer(instance, g_stSlaveIIC.rxbuf, g_stSlaveIIC.rxlength);
		if(pSlaveRxTask != NULL)
			cola_set_event(pSlaveRxTask, 0x01);
	}
	else if (slaveEvent == I2C_SLAVE_EVENT_TX_REQ)
	{//948 Read
		//read_commod(g_stSlaveIIC.rxbuf);
		I2C_SlaveSetTxBuffer(instance, g_stSlaveIIC.txbuf, g_stSlaveIIC.txlength);
	}
}

void bsp_drv_slave_iic_init(void)
{
	i2c_pal_lpi2c0_SlaveConfig0.callbackParam = (uint32_t *) &lpi2c0_instance;
	I2C_SlaveInit(&lpi2c0_instance, &i2c_pal_lpi2c0_SlaveConfig0);
}

void bsp_drv_slave_iic_deinit(void)
{
	I2C_SlaveDeinit(&lpi2c0_instance);
}

void bsp_drv_slave_iic_read(uint8_t *pBuf,int len)
{
	I2C_SlaveReceiveData(&lpi2c0_instance,pBuf,len);
}

void bsp_drv_slave_iic_write(const uint8_t *pBuf,int len)
{
	I2C_SlaveSendData(&lpi2c0_instance,pBuf,len);
}

void bsp_drv_slave_iic_ctrl_task(void *task)
{
	pSlaveRxTask = (task_t*)task;
}

void bsp_drv_slave_iic_ctrl_buf(void *task)
{
	ST_SLAVE_I2C_DATA *pData = (ST_SLAVE_I2C_DATA*)task;
	g_stSlaveIIC.rxbuf = pData->rxbuf;
	g_stSlaveIIC.rxlength = pData->rxlength;
	g_stSlaveIIC.txbuf = pData->txbuf;
	g_stSlaveIIC.txlength = pData->txlength;
	g_stSlaveIIC.fun = pData->fun;
	read_commod = g_stSlaveIIC.fun;
}
